<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="flex flex1" style="height: calc(100% - 82px)">
        <div class="left">
          <div>
            <div>案例列表</div>
            <el-button
              type="primary"
              v-if="has_role_list[3].has_role"
              @click="clear_form_data(), (show_box = true)"
              >新增案例</el-button
            >
          </div>
          <el-menu
            class="el-menu-vertical-demo"
            size="small"
            unique-opened
            :default-active="default_menu_id"
            @select="
              (e) => {
                select_menu(e)
              }
            "
          >
            <div v-for="item in case_tyleList" :key="item.id">
              <el-sub-menu :index="item.id">
                <template #title>
                  <span style="color: #333">{{ item.dictValue }}</span>
                </template>
                <div v-for="item1 in menu_list">
                  <div v-if="item1.type == item.dictCode">
                    <el-menu-item
                      v-for="item2 in item1.exampleList"
                      :index="item2.id"
                      :key="item2.id"
                      style="
                        width: 300px;
                        display: inline-block;
                        box-sizing: border-box;
                      "
                      class="text_over"
                      >{{ item2.name }}</el-menu-item
                    >
                  </div>
                </div>
              </el-sub-menu>
            </div>
          </el-menu>
        </div>
        <div class="right">
          <div v-if="case_info == ''" class="flex_cc flex_cm">
            <img src="@/assets/img/no_more.png" alt="" />
            <p class="tc c_999">暂无数据</p>
          </div>
          <div v-else>
            <div>
              <div>案例信息</div>
              <el-button
                type="primary"
                @click="edit"
                v-if="menu_list.length && has_role_list[1].has_role"
                >编辑</el-button
              >
            </div>
            <div
              style="
                height: calc(100% - 65px);
                overflow-y: auto;
                padding: 0 20px;
              "
            >
              <div class="desc_box">
                <div>
                  <span>案例名称：</span>
                  <el-tooltip :content="case_info?.name" placement="bottom">
                    <span class="text_over">{{ case_info?.name }}</span>
                  </el-tooltip>
                </div>
                <div>
                  <span>案例分类：</span>
                  <span v-for="item in case_tyleList">
                    <span
                      v-if="item.dictCode == case_info?.type"
                      style="color: #333"
                      >{{ item.dictValue }}</span
                    >
                  </span>
                </div>
                <div><span>排序：</span>{{ case_info?.sort }}</div>
                <div>
                  <span>状态：</span
                  ><span v-if="case_info?.status == 1">已启用</span>
                  <span v-else>已停用</span>
                </div>
              </div>
              <div class="flex_start" style="line-height: 40px">
                <span style="flex-shrink: 0">关键字：</span>
                <div
                  class="flex1"
                  style="
                    white-space: nowrap;
                    overflow-x: auto;
                    margin: 0 30px 0 0;
                  "
                >
                  {{ case_info?.keyWord }}
                </div>
              </div>
              <div class="flex_start" style="line-height: 40px; width: 100%">
                <span style="flex-shrink: 0">案例链接：</span>
                <!-- <div
                class="flex1"
                style="
                  white-space: nowrap;
                  overflow-x: auto;
                  margin: 0 30px 0 0;
                "
              >
                {{ case_info?.url }}
              </div> -->
                <a
                  @click="open(case_info?.url)"
                  class="flex1"
                  style="
                    display: inline-block;
                    word-break: break-word;
                    margin: 8px 0 8px 0;
                    line-height: 26px;
                    cursor: pointer;
                    color: #3580eb;
                    text-decoration: underline;
                  "
                >
                  {{ case_info?.url }}
                </a>
              </div>
              <div class="flex_start" style="line-height: 40px; width: 100%">
                <span style="flex-shrink: 0">案例简介：</span>
                <div
                  class="flex1"
                  style="
                    white-space: pre-wrap;
                    overflow-x: auto;
                    line-height: 26px;
                    margin: 8px 0 8px 0;
                  "
                >
                  {{ case_info?.description }}
                </div>
              </div>
              <div
                class="flex_start"
                style="line-height: 40px; height: calc(100% - 220px)"
              >
                <span style="flex-shrink: 0">案例头图：</span>
                <div class="flex1 flex_cc" style="height: 100%">
                  <img
                    :src="case_info?.picUrl"
                    style="max-width: 100%; max-height: 100%"
                    middle
                    alt=""
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      @close="resetForm(addcaseform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增成功案列</h4>
        <h4 v-else>编辑成功案例</h4>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          ref="addcaseform"
          label-width="100px"
        >
          <el-form-item label="案例名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="案例分类" prop="type">
            <el-select v-model="add_form_data.type">
              <el-option
                v-for="item in case_tyleList"
                :key="item.id"
                :label="item.dictValue"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="案例链接" prop="url">
            <el-input
              v-model="add_form_data.url"
              placeholder="请输入"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <el-form-item label="关键字" prop="keyWord">
            <el-input
              v-model="add_form_data.keyWord"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input
              v-model="add_form_data.sort"
              placeholder="请输入（不填写则默认为第一位）"
              show-word-limit
              maxlength="4"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio v-model="add_form_data.status" :label="1">启用</el-radio>
            <el-radio v-model="add_form_data.status" :label="0">停用</el-radio>
          </el-form-item>
          <el-form-item label="案例简介" prop="description">
            <el-input
              type="textarea"
              rows="4"
              resize="none"
              v-model="add_form_data.description"
              placeholder="请输入"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <el-form-item label="案例头图" prop="picUrl">
            <upload
              :imageUrl="add_form_data.picUrl"
              :width="285"
              :height="140"
              :limit="1"
              :accept="'image/jpeg,image/jpg,image/png'"
            ></upload>
          </el-form-item>
          <div class="m_top10 tr">
            <el-button @click="resetForm(addcaseform)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit(addcaseform)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, dictData } from '@/utils/utils' // 权限校验 字典数据
import search from '@/view/components/search.vue'
import upload from '@/view/components/upload.vue'
import { onMounted, ref, computed, nextTick, onUnmounted } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { getCookie } from '@/utils/cookie'
import { useStore } from 'vuex'
// 页面权限组
const has_role_list = ref([
  { path: 'success/list', has_role: false },
  { path: 'success/put', has_role: false },
  { path: 'success/delete', has_role: false },
  { path: 'success/post', has_role: false },
])
nextTick(() => {
  has_role_list.value.forEach((item) => {
    if (check_role(item.path)) {
      item.has_role = true
    }
  })
})
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addcaseform = ref<FormInstance>()
const rules = ref({
  name: [{ required: true, message: '请输入案例名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择案例分类', trigger: 'change' }],
  url: [{ required: true, message: '请输入案例链接', trigger: 'blur' }],
  keyWord: [{ required: true, message: '请输入关键字', trigger: 'blur' }],
  description: [{ required: true, message: '请输入案例简介', trigger: 'blur' }],
  picUrl: [{ required: true, message: '请上传案例头图', trigger: 'change' }],
})
const header_list = ref([
  {
    label: '案例名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: true,
    options: [
      { label: '已启用', value: '1' },
      { label: '已停用', value: '0' },
    ],
  },
])
const menu_list = ref([]) // 左侧列表使用
const default_menu_id = ref()
const page_data = ref({
  status: '',
  name: '',
})
const add_form_data = ref({
  id: '',
  name: '',
  sort: '',
  description: '',
  picUrl: [],
  status: 1,
  type: '',
  url: '',
  keyWord: '',
})
const is_uploadImg = computed(() => {
  return add_form_data.value.picUrl.length
})
const member_page_data = ref({
  current: 1,
  pageSize: 10,
  deptId: '',
  enterpriseId:
    store.state.enterprise_id != '' // 当前登录企业 vuex > cookie
      ? store.state.enterprise_id
      : getCookie('enterprise_id'),
})
const open = (e) => {
  window.open(e)
}
const show_box = ref(false)
// 案列类型
const case_tyleList = computed(() => {
  return store.state.product_list
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('uploadSucc')
})
onMounted(() => {
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  EventBus.on('uploadSucc', () => {
    // 上传图片成功 取消验证提示
    console.log(is_uploadImg)
    if (is_uploadImg.value) {
      addcaseform.value.clearValidate(['picUrl'])
    }
  })
  get_list()
})
const btn_loading = ref(false)
const current_name = ref('')
const submit = async (formEl: FormInstance | undefined) => {
  let data = JSON.parse(JSON.stringify(add_form_data.value))
  data.picUrl = data.picUrl.toString()
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) {
        return
      }
      btn_loading.value = true
      current_name.value = data.name
      axios
        .request({
          url:
            data.id == ''
              ? serviceApi.suuc_case_crud
              : serviceApi.suuc_case_crud + '/' + data.id,
          method: data.id == '' ? 'post' : 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            show_box.value = false
            btn_loading.value = false
            resetForm(formEl)
            get_list()
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const get_list = () => {
  axios
    .request({
      url: serviceApi.suuc_case_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      menu_list.value = res.data
      if (res.data.length) {
        if (current_name.value == '') {
          default_menu_id.value = res.data[0].exampleList[0].id
        } else {
          res.data.forEach((i) => {
            i.exampleList.some((ii) => {
              if (ii.name == current_name.value) {
                default_menu_id.value = ii.id
              }
              return ii.name == current_name.value
            })
          })
        }
        get_case_info()
      } else {
        case_info.value = ''
      }
    })
}
const edit = () => {
  if (add_form_data.value.id == '') {
    get_case_info()
  }
  show_box.value = true
}
const case_info = ref()
const get_case_info = () => {
  axios
    .request({
      url: serviceApi.suuc_case_crud + '/' + default_menu_id.value,
      method: 'get',
    })
    .then((res) => {
      console.log(res)
      member_page_data.value.deptId = res.data.id
      add_form_data.value = {
        id: res.data.id,
        name: res.data.name,
        sort: res.data.sort,
        description: res.data.description,
        picUrl: [res.data.picUrl],
        status: res.data.status,
        type: res.data.type + '',
        url: res.data.url,
        keyWord: res.data.keyWord ? res.data.keyWord : '',
      }
      case_info.value = JSON.parse(JSON.stringify(add_form_data.value))
    })
}
const select_menu = (e) => {
  console.log(e)
  default_menu_id.value = e
  get_case_info()
}

const search_key = () => {
  page_data.value = {
    status: header_list.value[1].value,
    name: header_list.value[0].value,
  }
  get_list()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  clear_form_data()
  show_box.value = false
}
const clear_form_data = () => {
  add_form_data.value = {
    id: '',
    name: '',
    sort: '',
    description: '',
    picUrl: [],
    status: 1,
    type: '',
    url: '',
    keyWord: '',
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-menu) {
  .el-sub-menu__title {
    background-color: #fff;
    &:hover {
      background-color: #fff;
    }
  }
  --el-menu-text-color: #333;
  --el-menu-hover-text-color: #333;
  --el-menu-bg-color: #fff;
  --el-menu-hover-bg-color: #fff;
}
:deep(.el-menu) {
  border-right: none;
}
.left {
  width: 300px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #fff;
  > div:first-child {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    border-bottom: 1px solid #d8d8d8;
  }
}
.right {
  flex: 1;
  height: 100%;
  width: calc(100% - 320px);
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  > div:first-child {
    background-color: #fff;
    > div:first-child {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 20px;
      border-bottom: 1px solid #d8d8d8;
    }

    .desc_box {
      padding: 10px 20px 0 0;
      line-height: 40px;
      display: flex;
      flex-wrap: wrap;
      div {
        width: 24%;
        padding-right: 1%;
        display: flex;
        > span:first-child {
          flex-shrink: 0;
        }
      }
    }
    span:first-child {
      color: #999;
    }
  }
  > div:last-child {
    flex: 1;
    height: 100%;
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }
}
</style>
